package com.xrf;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import net.java.handlers.RequestCycleHandler;
import net.java.localization.LocalizedMessages;
import net.java.tool.Compatibility;

public class CheckTag extends TagSupport {
    private static final long serialVersionUID = -6834095891675681686L;
    private static final String FILE_UPLOAD = "FileUpload";
    private static final String GET_RESOURCES = "GetResources";
    private static final String CREATE_FOLDER = "CreateFolder";
    private static final String COMPATIBLE_BROWSER = "CompatibleBrowser";
    private static final Set<String> commands = new HashSet<>(4);
    
    private String command;
    
    public void setCommand(String command) throws JspTagException {
        if (!commands.contains(command)) {
            throw new JspTagException("You have to provide one of the following commands: " + commands);
        }
        this.command = command;
    }
    
    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        LocalizedMessages lm = LocalizedMessages.getInstance(request);
        String response = "";
        
        if (this.command.equals("FileUpload")) {
            if (RequestCycleHandler.isFileUploadEnabled(request))
                response = lm.getFileUploadEnabled();
            else {
                response = lm.getFileUploadDisabled();
            }
        }
        if (this.command.equals("GetResources")) {
            if (RequestCycleHandler.isGetResourcesEnabled(request))
                response = lm.getGetResourcesEnabled();
            else {
                response = lm.getGetResourcesDisabled();
            }
        }
        if (this.command.equals("CreateFolder")) {
            if (RequestCycleHandler.isCreateFolderEnabled(request))
                response = lm.getCreateFolderEnabled();
            else {
                response = lm.getCreateFolderDisabled();
            }
        }
        if (this.command.equals("CompatibleBrowser")) {
            if (Compatibility.isCompatibleBrowser(request))
                response = lm.getCompatibleBrowserYes();
            else
                response = lm.getCompatibleBrowserNo();
        }
        try {
            out.print(response);
        } catch (IOException e) {
            throw new JspException("Tag response could not be written to the user!", e);
        }
        return 0;
    }
    
    static {
        commands.add("FileUpload");
        commands.add("CompatibleBrowser");
        commands.add("GetResources");
        commands.add("CreateFolder");
    }
}